package com.lap.context.starter.interceptor;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.lap.framework.constant.Header;
import com.lap.context.starter.autoconfigure.properties.ContextProperties;
import com.lap.context.starter.entity.ContextDefinition;
import com.lap.context.starter.entity.UserInfo;
import com.lap.context.starter.helper.UserHelper;
import com.lap.context.starter.tools.HttpRequestUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 默认上下文装载器，您也可以根据自己需要装载
 *
 * @author Shuisheng Lao(劳水生)
 * @version 1.0.0
 */
@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {

  @Resource
  private ContextProperties properties;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) {
    Integer userId = HttpRequestUtil.getInteger(request, Header.USER_ID);
    if (userId != null) {
      ContextDefinition context = new UserInfo();
      context.setUserId(userId);
      context.setUsername(HttpRequestUtil.getString(request, Header.USER_NAME));
      context.setFullName(HttpRequestUtil.getString(request, Header.FULL_NAME, true));
      context.setMap(customizer(request));

      UserHelper.set(context);
      log.info("context::{}", context);
    }
    return true;
  }

  protected Map<String, String> customizer(HttpServletRequest request) {
    if (Objects.isNull(properties) || CollectionUtils.isEmpty(properties.getParameters()))
      return Collections.emptyMap();

    Map<String, String> result = new HashMap<>(properties.getParameters().size());
    for (ContextProperties.Prop prop : properties.getParameters()) {
      String value = HttpRequestUtil.getString(request, prop.getKey(), prop.isEncode());
      if (StringUtils.isNotBlank(value)) {
        result.put(prop.getKey(), value);
      }
    }
    return result;
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) {
    UserHelper.remove();
  }
}
